﻿using Cinemachine;
using UnityEngine;

namespace HEFramework
{
    public static class GameCameraSystem
    {
        [EntitySystem]
        public class GameCameraAwakeSystem : AwakeSystem<GameCamera>
        {
            protected override void Awake(GameCamera _self)
            {
                var gc = _self.AddChild<GameObjectComponent>();
                var rc = _self.GetSceneChild<ResourcesComponent>();
                if (gc == null || rc == null)
                {
                    return;
                }

                _self.SceneCamera = GameObject.Find("Main").transform.Find("SceneCamera").GetComponent<Camera>();
                _self.UICamera = GameObject.Find("Main").transform.Find("UICamera").GetComponent<Camera>();
                var obj = rc.Assets.LoadAssetSyn<GameObject>("2d/prefabs/camera", "Camera_Game", ResourceConfig.Extension.PREFAB);
                gc.GameObject = GameObject.Instantiate(obj);
                gc.GameObject.transform.position = Vector2.zero;
            }
        }


        [EntitySystem]
        public class GameCameraUpdateSystem : UpdateSystem<GameCamera>
        {
            protected override void Update(GameCamera _self)
            {
            }
        }


        [EntitySystem]
        public class GameCameraDestroySystem : DestroySystem<GameCamera>
        {
            protected override void Destroy(GameCamera _self)
            {
            }
        }


        public static void SetTarget(this GameCamera _self, Transform _obj)
        {
            if (_obj != null)
            {
                int id = _obj.GetInstanceID();
                if (_self.TargetID == id)
                {
                    return;
                }

                var obj = _self.GetChild<GameObjectComponent>().GameObject;
                if (obj == null)
                {
                    return;
                }

                var camera = obj.GetComponent<CinemachineVirtualCamera>();
                camera.LookAt = camera.Follow = _obj.transform;
                _self.TargetID = id;
            }
            else
            {
                int id = 0;
                if (_self.TargetID == id)
                {
                    return;
                }

                var obj = _self.GetChild<GameObjectComponent>().GameObject;
                if (obj == null)
                {
                    return;
                }

                var camera = obj.GetComponent<CinemachineVirtualCamera>();
                camera.Follow = null;
                camera.LookAt = null;
                _self.TargetID = id;
            }
        }

        public static void SetGameObjectRotateToCamera(this GameCamera _self, Transform _obj)
        {
            if (_obj == null)
            {
                return;
            }

            _obj.transform.rotation = _self.SceneCamera.transform.rotation;
        }
    }
}